﻿/*
 * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 * See https://github.com/openiddict/openiddict-core for more information concerning
 * the license and the contributors participating to this project.
 */

using System.ComponentModel;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Extensions.Options;
using OpenIddict.Client.SystemNetHttp;
using static OpenIddict.Client.WebIntegration.OpenIddictClientWebIntegrationConstants;

namespace OpenIddict.Client.WebIntegration;

/// <summary>
/// Contains the methods required to ensure that the OpenIddict client Web integration configuration is valid.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public sealed partial class OpenIddictClientWebIntegrationConfiguration : IConfigureOptions<OpenIddictClientOptions>,
                                                                          IPostConfigureOptions<OpenIddictClientOptions>,
                                                                          IPostConfigureOptions<OpenIddictClientSystemNetHttpOptions>
{
    /// <inheritdoc/>
    public void Configure(OpenIddictClientOptions options)
    {
        if (options is null)
        {
            throw new ArgumentNullException(nameof(options));
        }

        // Register the built-in event handlers used by the OpenIddict client Web components.
        options.Handlers.AddRange(OpenIddictClientWebIntegrationHandlers.DefaultHandlers);
    }

    /// <inheritdoc/>
    public void PostConfigure(string? name, OpenIddictClientOptions options)
    {
        if (options is null)
        {
            throw new ArgumentNullException(nameof(options));
        }

        options.Registrations.ForEach(static registration =>
        {
            // If the client registration has a provider type attached, apply
            // the configuration logic corresponding to the specified provider.
            if (!string.IsNullOrEmpty(registration.ProviderType))
            {
                ConfigureProvider(registration);
            }
        });
    }

    /// <inheritdoc/>
    public void PostConfigure(string? name, OpenIddictClientSystemNetHttpOptions options)
    {
        if (options is null)
        {
            throw new ArgumentNullException(nameof(options));
        }

        // Override the default/user-defined selectors to support attaching TLS client
        // certificates that don't meet the requirements enforced by default by OpenIddict.
        options.SelfSignedTlsClientAuthenticationCertificateSelector = CreateSelector(options.SelfSignedTlsClientAuthenticationCertificateSelector);
        options.TlsClientAuthenticationCertificateSelector = CreateSelector(options.TlsClientAuthenticationCertificateSelector);

        static Func<OpenIddictClientRegistration, X509Certificate2?> CreateSelector(Func<OpenIddictClientRegistration, X509Certificate2?> selector)
            => registration =>
            {
                var certificate = registration.ProviderType switch
                {
                    ProviderTypes.ProSantéConnect => registration.GetProSantéConnectSettings().SigningCertificate,

                    _ => null
                };

                if (certificate is not null)
                {
                    return certificate;
                }

                return selector(registration);
            };
    }

    /// <summary>
    /// Amends the registration with the provider-specific configuration logic.
    /// </summary>
    /// <param name="registration">The client registration.</param>
    // Note: the implementation of this method is automatically generated by the source generator.
    [EditorBrowsable(EditorBrowsableState.Never)]
    public static partial void ConfigureProvider(OpenIddictClientRegistration registration);
}
